<template>
	<view class="content-box">
		<word-review
			v-if="inStep === 1"
			:wordlist="stepData"
			@next="handelTestNext"
			:mode="0"
		/>
		<view class="detail" v-else-if="inStep === 2">
			<single-selection v-if="visibleSingleSelection" :show-timer="showTimer" v-bind="testAttrs" @next="getNextflag" />
			<spell-word v-if="visibleSpellWord" :show-timer="showTimer" v-bind="testAttrs" @next="getNextflag" />
			<with-fill-sentence
				v-if="visibleSentenceTest"
				:word-list="sentenceWordList"
				:timer-bar-sty="timerBarSty"
				:show-timer="showTimer"
				@update-group="handleUpdateGroup"
				@next="handleNext"
			/>
		</view>
		<lv-result v-else @next="handelNext" :isteacher="isteacher" :isreview="isreview" :reviewles="reviewles" />
		<u-modal v-model="showCoinBox" @confirm="confirmCoinBox" :title-style="{color: 'red'}">
			<view class="h-20px"></view>
			<view class="text-center">
				恭喜你获得{{Coin}}颗小五豆
			</view>
			<view class="h-20px"></view>
		</u-modal>
	</view>
</template>

<script lang="ts" setup>
	import { ref, onMounted, computed, nextTick, provide } from 'vue';
	import { IUseTemplate, IWord, TestTemplate, TestTemplates, useStudyStore } from '@/store/study';
	import { OT, deepClone, isEmpty, ktlapi, lodash, getUuid } from '@/utils';
	import { useTest } from '@/common/hooks';
	import WordReview from '@/pages-study/components/word-review/word-review.vue';
	import SingleSelection from '@/pages-study/components/single-selection/single-selection.vue';
	import SpellWord from '@/pages-study/components/spell-word/spell-word.vue';
	import LvResult from '@/pages-study/components/lv-result/lv-result.vue';
	import WithFillSentence from '@/pages-study/components/fill-sentence/with-fill-sentence.vue';
	
	type IProps = {
		errLearn?: boolean;
		isreview?: number;
		reviewles?: string;
		isteacher?: number;
		sentenceTest?: boolean;
		timerBarSty?: string;
		showTimer?: boolean;
	}
	
	/** 步骤：单词组测试 */
	defineOptions({
		name: 'step-group-test',
		inheritAttrs: false,
		options: {
			virtualHost: true
		}
	});
	// 声明组件基本要素
	const emit = defineEmits(['module-event']);
	const props = withDefaults(defineProps<IProps>(),{
		errLearn: false,
		isreview: 0,
		isteacher:0,
		reviewles: '',
		sentenceTest: true,
		timerBarSty: '',
		showTimer: false
	});
	
	provide('isteacher', props.isteacher);
	provide('isreview', props.isreview);
	provide('doubleVisible', false);
	// hooks 初始化
	const studyStore = useStudyStore();
	const testUtil = useTest();
	
	// 声明用户变量
	const { SPELL, SPELL_SIMPLE, SPELL_SYLLABLE, YYH, HYY, TX, SENTENCE_TEST } = TestTemplates;
	const stepData = ref<IWord[]>([]);
	// 惩罚机制
	const CFCount = 3;
	const inStep = ref(1);
	const testAttrs = ref<any>({});
	// 当前测试类型
	const currentType = ref<any>({});
	const SingleTemplates = [YYH, HYY, TX];
	const SpellTemplates = [SPELL, SPELL_SIMPLE, SPELL_SYLLABLE];
	
	const showCoinBox = ref(false);
	const Coin = ref(0);
	
	// 单选组件显示状态
	const visibleSingleSelection = ref(false);
	// 单词拼写显示状态
	const visibleSpellWord = ref(false);
	// 句词测试显示状态
	const visibleSentenceTest = ref(false);
	// 句词测试数据源
	const sentenceWordList = computed(() => {
		return stepData.value.filter(sd => sd.NeedRemeber);
	})

	function confirmCoinBox() {
		
	}

	/** 测试下一题 */
	function handelTestNext() {
		inStep.value = 2;
		const result = testUtil.findCurrent(stepData.value);
		if (result.found) {
		
			// console.log('result.found', result.found)
			const { type } = result.attrs;
			
			// 前一测试类型属于[单选模板]
			if (testUtil.hasTemplate(SingleTemplates, currentType.value)) {
				// 新的测试类型不属于[单选模板]，隐藏[单选模板]
				if(!testUtil.hasTemplate(SingleTemplates, type)) {
					visibleSingleSelection.value = false;
				}
			}
			// 前一测试类型属于[拼写模板]
			else if (testUtil.hasTemplate(SpellTemplates, currentType.value)) {
				// 新的测试类型不属于[拼写模板]，隐藏[拼写模板]
				if(!testUtil.hasTemplate(SpellTemplates, type)) {
					visibleSpellWord.value = false;
				}
			}
			
			// 新的测试类型属于[单选模板], 显示[单选模板]
			if (testUtil.hasTemplate(SingleTemplates, type)) {
				visibleSingleSelection.value = true;
			}
			// 新的测试类型属于[拼写模板], 显示[拼写模板]
			if (testUtil.hasTemplate(SpellTemplates, type)) {
				visibleSpellWord.value = true;
			}

			nextTick().then(() => {
				currentType.value = type;
				testAttrs.value = {
					...result.attrs,
					effect: true,
					jump: true,
					errLearn: props.errLearn,
					timerBarSty: props.timerBarSty
				};
			})
			return;
		}
		
		// 如果启动[句词测试模板]，显示[句词测试模板]
		if (props.sentenceTest) {
			visibleSingleSelection.value = false;
			visibleSpellWord.value = false;
			visibleSentenceTest.value = true;
		} else {
			// 否则进入最终结算
			finalSettlement();
		}
	}
	
	/** 最终结算 */
	function finalSettlement() {
		if(props.isreview==1){
			var subData = [];
			for(var i=0;i<stepData.value.length;i++){
				subData.push({
					"ID":stepData.value[i]["ID"],
					"LostLv":stepData.value[i]["LostLv"],
					"ReviewUUID":(props.reviewles==""?studyStore.LessonUUID:props.reviewles)
				});
			}
			ktlapi({
				apiurl: OT.CommandAddSet,
				action: 'Cus_RemeberReviewTimer',
				data: subData
			}).then(res => {
				console.log('res', res)
				
				subReviewData();
			});
		}else{ 
			subReviewData();
			emit('module-event', { action: 'refreshcnt' })
		} 
	}
	
	// 最终结算扩展函数
	function subReviewData(){
		// visibleSingleSelection.value = false;
		// visibleSpellWord.value = false;
		// visibleSentenceTest.value = false;
		var subData = [];
		for (let i = 0; i < stepData.value.length; i++) {
			const wordItem = stepData.value[i];
			const wIdx = studyStore.wordGroup.findIndex(item => item.WordId === wordItem.WordId);
			if (!wordItem.NeedRemeber) {
				wordItem.LostLv = 0;
				// 同步 studyStore.wordGroup 数据
				if (wIdx > -1) {
					studyStore.wordGroup[wIdx].LostLv = 0;
				}
				continue;
			}
			
			wordItem.LostLv = isEmpty(wordItem.LostLv) ? 18 : wordItem.LostLv;
			// 结算单频测试模板
			wordItem.LostLv = wordItem.UseTemplates.reduce((prev, curr) => {
				const weight = curr.template.weight;
				const count = prev + (curr.ErrorCount > 0 ? weight : -weight);
				if (count < 0) return 0;
				if (count > 18) return 18;
				return count;
			}, wordItem.LostLv);
			// 结算组合测试模板
			wordItem.LostLv = wordItem.UseCombTemplates.reduce((prev, curr) => {
				const weight = curr.template.weight;
				const count = prev + (curr.ErrorCount > 0 ? weight : -weight);
				if (count < 0) return 0;
				if (count > 18) return 18;
				return count;
			}, wordItem.LostLv);

			for(var k=0;k<wordItem.UseTemplates.length;k++){
				var row = wordItem.UseTemplates[k];
				if(wordItem["LostLv"] == 0 && row["ErrorCount"] > 0){
					wordItem["LostLv"] = 1;
					break;
				}
			}
			for(var k=0;k<wordItem.UseCombTemplates.length;k++){
				var row = wordItem.UseTemplates[k];
				if(wordItem["LostLv"] == 0 && row["ErrorCount"] > 0){
					wordItem["LostLv"] = 1;
					break;
				}
			}
			
			if (wordItem.LostLv > 18) wordItem.LostLv = 18;
			if (wordItem.LostLv < 0) wordItem.LostLv = 0;
			
			// 同步studyStore.wordGroup数据
			if (wIdx > -1) {
				studyStore.wordGroup[wIdx].LostLv = wordItem.LostLv;
			}
			subData.push({
				ID: wordItem.ID,
				SentenceSnapshot: JSON.stringify(wordItem.SentenceSnapshot),
				LostLv: wordItem.LostLv,
				IsFinished: 1
			});
		}
		// 提交数据
		ktlapi({
			apiurl: OT.CommandAddSet,
			action: 'Cus_UpdateRemeberProcess',
			data: subData
		}).then(res => {
			console.log('res', res)
			console.log("props.isreview", props.isreview)
			// 自主复习
			if (props.isteacher === 0 && props.isreview) {
				ktlapi({
					action: 'Cus_CoinCustomReview',
					data: {
						Ids: subData.map(item => item.ID).join(',')
					}
				}).then((resp: any) => {
					Coin.value = resp.data[0].Coin
					if (Coin.value) {
						showCoinBox.value = true;
					}
				})
			}
			
			// 更新统计数据 
		})
		inStep.value = 3; 
	}
	
	/** 测试结算(单次) */
	function getNextflag(_item: IWord, isright: boolean, isJump: boolean){
		const { type, current } = testAttrs.value;
		for (let i = 0; i < stepData.value.length; i++) {
			const item = stepData.value[i];
			if (current.WordId === item.WordId) {
				for (let i = 0; i < item.UseTemplates.length; i++) {
					if (testUtil.getTemplateType(item.UseTemplates[i]) == testUtil.getTemplateType(type)) {
						item.UseTemplates[i]["TotalCount"] -= 1;
						if(!isright){
							item.UseTemplates[i]["ErrorCount"] += 1;
							item.UseTemplates[i]["TotalCount"] += CFCount;  
				
							if (isJump) {
								item.UseTemplates[i]["TotalCount"] = 0;
							} else if (item.UseTemplates[i]["TotalCount"] > CFCount){
								item.UseTemplates[i]["TotalCount"] = CFCount
							}
						}
						break;
					}
				}
				break;
			}
		}
		
		handelTestNext();
	}
	
	// 句词测试，单组测试完成
	function handleUpdateGroup(sentenceEn: string, isRight: boolean, answer: any[]) {
		console.log('step-group-test >>> handleUpdateGroup >>> sentenceEn = ', sentenceEn)
		console.log('step-group-test >>> handleUpdateGroup >>> isRight = ', isRight)
		console.log('step-group-test >>> handleUpdateGroup >>> answer = ', answer)
		console.log('step-group-test >>> handleUpdateGroup === 句词测试，单组测试完成')
		
		stepData.value.forEach(sd => {
			answer.forEach(ans => {
				if (ans.WordId === sd.WordId) {
					// 更新组合测试模板数据
					sd.UseCombTemplates.forEach(uct => {
						if (testUtil.getTemplateType(uct) === testUtil.getTemplateType(SENTENCE_TEST)) {
							uct.TotalCount--;
							if (ans.IsRight) {
								uct.ErrorCount = 0;
							} else {
								uct.ErrorCount = 1;
							}
						}
					})
				}
			})
		})
	}
	
	// 全部完成，下一步
	function handleNext() {
		console.log('step-group-test >>> handleNext === 全部完成，下一步')
		// 进入最终结算
		finalSettlement();
	}
	
	onMounted(() => {
		let useTemplates: TestTemplate[] = [];
		if (studyStore.tester.isTestMode) {
			const { testHYY, testYYH, testTX, testSPELL_SYLLABLE } = studyStore.tester;
			if (testHYY) useTemplates.push(HYY);
			if (testYYH) useTemplates.push(YYH);
			if (testTX) useTemplates.push(TX);
			if (testSPELL_SYLLABLE) useTemplates.push(SPELL_SYLLABLE);
		} else {
			useTemplates = [HYY, YYH, TX, SPELL_SYLLABLE];
		}
		
		const useCombTemplates: TestTemplate[] = [];
		if (props.sentenceTest) {
			if (studyStore.tester.isTestMode) {
				if (studyStore.tester.testSENTENCE_TEST) {
					useCombTemplates.push(SENTENCE_TEST);	
				}
			} else {
				useCombTemplates.push(SENTENCE_TEST);
			}
		}
		if (studyStore.wordGroup.length > 0) {
			uni.showLoading({ title: '加载中' })	
		}
		const cloneWords: IWord[] = JSON.parse(JSON.stringify(studyStore.wordGroup)); 
		//console.log("studyStore.wordGroup",studyStore.wordGroup)
		const needRemeberWords: IWord[] = cloneWords.filter(item => item.NeedRemeber);
		needRemeberWords.forEach(wordInfo => {
			let tempUseTemplates = [...useTemplates]
			// wordInfo.Word = 'aaabbbccc'
			// wordInfo.Syllable = 'aaa/bbb/ccc'
			if (wordInfo.NeedWrite) {
				const { isTestMode, testSPELL, testSPELL_SIMPLE } = studyStore.tester;
				if(wordInfo.Word.length > 6) {
					if (isTestMode) {
						if (testSPELL_SIMPLE) {
							useCombTemplates.push(SPELL_SIMPLE);
						}
					} else {
						tempUseTemplates.push(SPELL_SIMPLE)
					}
				} else {
					if (isTestMode) {
						if (testSPELL) {
							useCombTemplates.push(SPELL);
						}
					} else {
						tempUseTemplates.push(SPELL)
					}
				}
			}
			
			// 兜底，如果没有任何模板，则默认加一个英译汉
			if (tempUseTemplates.length === 0) {
				tempUseTemplates.push(HYY);
			}

			// 针对音节拼写，需要排除不规范的内容
			if(testUtil.isExistSyllableTemp(tempUseTemplates)) {
				tempUseTemplates = testUtil.templatesNormalize(tempUseTemplates, wordInfo);
			}
			wordInfo.UseTemplates = testUtil.initUseTemplateConfig(tempUseTemplates, { TotalCount: 1, ErrorCount: 0 })
			// 配置组合模板
			wordInfo.UseCombTemplates = testUtil.initUseTemplateConfig(useCombTemplates, { TotalCount: 1, ErrorCount: 0 })
		});

		// 添加混淆项
		testUtil.fillTestData(needRemeberWords, [...studyStore.wordGroup, ...studyStore.shuffleWords]);
		stepData.value = needRemeberWords;
	})
	
	const handelNext = () => {
		emit('module-event', { action: 'next' });
	}
</script>


<style lang="scss" scoped>
	.content-box{
		--font-color: #332c2b;
		display: flex;
		flex-flow: column;
		flex: 1;
		margin: 0 30rpx;
		
		.option-box {
			display: flex;
			height: 100rpx;
			align-items: center;
		
			.left {
				flex: 1;
				display: flex;
				align-items: center;
		
				.read-text {
					color: #757475;
					margin-right: 20rpx;
					font-size: var(--text-18);
				}
			}
		
			.process {
				padding: 10rpx 14rpx;
				color: #f55f22;
				background-color: #fed7c6;
				border-radius: 30rpx;
				min-width: 150rpx;
				text-align: center;
			}
		}
		
		.detail {
			flex: 1;
			padding-top: 15rpx;
			display: flex;
			flex-flow: column;
		}
	}
	
	.next-btn{
		/* #ifdef H5 */
		height: 45px !important;
		/* #endif */
	}
	.next-text{
		font-size: var(--text-16);
		font-weight: bold;
		display: flex;
	}
	
	/* 针对 1280px 分辨率 */
	@media(min-width:1200px) {
		.content-box {
			width: 2400rpx;
			margin: 0 auto !important;
		}
		
		.process{
			min-width: 238rpx;
		}
	
		.detail {
			
		}
	}
</style>